package com.qilu.pe.ui.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.androidkun.xtablayout.XTabLayout;
import com.qilu.pe.R;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Config;
import com.qilu.pe.base.Global;
import com.qilu.pe.dao.bean.Article;
import com.qilu.pe.dao.bean.Banner;
import com.qilu.pe.dao.bean.Msg;
import com.qilu.pe.dao.bean.UnreadData;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.GlideUtil;
import com.qilu.pe.support.util.Logg;
import com.qilu.pe.ui.activity.ArticleDetailActivity;
import com.qilu.pe.ui.activity.ArticleListActivity;
import com.qilu.pe.ui.activity.MsgListActivity;
import com.qilu.pe.ui.activity.PlaceOrderActivity;
import com.qilu.pe.ui.activity.ReportExplainActivity;
import com.qilu.pe.ui.activity.SearchActivity;
import com.qilu.pe.ui.adapter.ArticleAapter;
import com.qilu.pe.ui.adapter.CustomViewpager;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.BaseFragment;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.support.view.MeasuredViewPager;
import com.ruitu.arad.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

// 首页
public class Home1Fragment extends BaseFragment {
    //    private Banner banner;
    private static Home1Fragment fragment;
    protected ViewPager vp;// banner
    private XTabLayout tab_2;
//    private MeasuredViewPager vp_tab;
    private CustomViewpager vp_tab;
    private RecyclerView rcv_article;// 精选文章
    private RelativeLayout rl_3, rl_report_explain, rl_place_order, rl_search;// 精选文章,报告解读,下单,搜索
    private ImageView iv_notice;// 消息
    private TextView tv_city, vUnreadCount;

    private VpAdapter adapter;// banner
    private VpTabAdapter vpTabAdapter;// tab
    private ArticleAapter articleAapter;// 精选文章
    private static final String[] HOME_MODELS = {"特色项目", "特色套餐"};

    private List<Banner> bannerList = new ArrayList<>();// banner的数据
    private List<Article> articleList = new ArrayList<>();
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    mViewPageSwitchCount++;
                    vp.setCurrentItem(mViewPageSwitchCount % bannerList.size(), true);
                    mHandler.sendEmptyMessageDelayed(1, 6 * 1000);
                    break;
                case 2:
                    refreshUnreadMsg();
                    break;
            }

        }
    };
    private int mViewPageSwitchCount = 0;

    private LocationManager lm;

    public Home1Fragment() {

    }

    public static Home1Fragment newInstance() {
        if (fragment == null) {
            fragment = new Home1Fragment();
            Bundle args = new Bundle();
            fragment.setArguments(args);
        }
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        lm = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

        mHandler.sendEmptyMessageDelayed(1, 6 * 1000);
    }

    private void initGps() {
        // 从gps获取最近的定位信息
        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        Location lc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        updateShow(lc);
        //设置间隔两秒获得一次gps定位信息
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000, 8, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                // 当gps定位信息发生改变时,更新定位
                updateShow(location);
            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {
            }

            @Override
            public void onProviderEnabled(String provider) {
                // 当gpsLocationProvider可用时,更新定位
                if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                        && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                updateShow(lm.getLastKnownLocation(provider));
            }

            @Override
            public void onProviderDisabled(String s) {
                updateShow(null);
            }
        });
    }

    // 定义更新显示的方法
    private void updateShow(final Location location) {
        if (location != null) {
            StringBuilder sb = new StringBuilder();
            sb.append("当前位置定位信息:\n");
            sb.append("经度:" + location.getLongitude() + "\n");
            sb.append("维度:" + location.getLatitude() + "\n");
            sb.append("海拔:" + location.getAltitude() + "\n");
            sb.append("速度:" + location.getSpeed() + "\n");
            sb.append("方位:" + location.getBearing() + "\n");
            sb.append("时间:" + location.getTime() + "\n");
            sb.append("定位精度:" + location.getLongitude() + "\n");
//            Logg.i("sb.toString() = " + sb.toString());
            new Thread(new Runnable() {
                @Override
                public void run() {
                    getAddress(location);
                }
            }).start();
        } else {
            tv_city.setText("定位失败");
            Logg.i("定位失败...");
        }
    }

    List<Address> result = null;

    // 获取地址信息
    private List<Address> getAddress(Location location) {
        try {
            if (location != null) {
                Geocoder gc = new Geocoder(getActivity(), Locale.getDefault());
                result = gc.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

                for (int i = 0; i < result.size(); i++) {
                    Logg.i("result " + i + " = " + result.get(i).toString());
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        String city = "";
                        try {
                            city = result.get(0).getSubAdminArea();
                            if (TextUtils.isEmpty(city)) {
                                city = result.get(0).getLocality();
                            }
                            if (TextUtils.isEmpty(city)) {
                                city = "定位中";
                            }
                            tv_city.setText(city);
                        } catch (Exception e) {
                            e.printStackTrace();
                            tv_city.setText("定位失败");
                        }
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_home1, container, false);
//        banner = v.findViewById(R.id.banner);// Banner布局
        vp = v.findViewById(R.id.vp);// Banner布局
        tab_2 = v.findViewById(R.id.tab_2);
        vp_tab = v.findViewById(R.id.vp_tab);
        rcv_article = v.findViewById(R.id.rcv_article);
        rl_3 = v.findViewById(R.id.rl_3);
        rl_report_explain = v.findViewById(R.id.rl_report_explain);
        rl_place_order = v.findViewById(R.id.rl_place_order);
        iv_notice = v.findViewById(R.id.iv_notice);
        tv_city = v.findViewById(R.id.tv_city);
        rl_search = v.findViewById(R.id.rl_search);
        vUnreadCount = v.findViewById(R.id.vUnreadCount);

        adapter = new VpAdapter();
        vp.setAdapter(adapter);

        for (int i = 0; i < 2; i++) {
            tab_2.addTab(tab_2.newTab().setText(HOME_MODELS[i]), i);
        }
        vpTabAdapter = new VpTabAdapter(getChildFragmentManager());
        vp_tab.setAdapter(vpTabAdapter);
        tab_2.setupWithViewPager(vp_tab);

        articleAapter = new ArticleAapter(getActivity());
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        rcv_article.setLayoutManager(manager);
        rcv_article.setAdapter(articleAapter);
        vp_tab.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                vp_tab.resetHeight(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        vp_tab.resetHeight(0);
        setListeners();

        reqBannerList();// 请求banner列表
        reqArticleList();// 请求文章列表

//        initGps();// 开始定位
        return v;
    }

    private void setListeners() {
        setOnClickListener(rl_3, rl_report_explain, iv_notice, rl_place_order, rl_search);
        articleAapter.setOnItemClickListener(new ListBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int position) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("article", articleList.get(position));
                startActivity(ArticleDetailActivity.class, bundle);
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v == rl_search) {// 搜索
            startActivity(SearchActivity.class);
        }
        if (v == rl_3) {// 精选文章列表
            startActivity(ArticleListActivity.class);
        }
        if (v == rl_report_explain) {// 报告解读
            startActivity(ReportExplainActivity.class);
        }
        if (v == iv_notice) {// 消息
            startActivityForResult(new Intent(getActivity(), MsgListActivity.class), 1001);
        }
        if (v == rl_place_order) {// 下单
            startActivity(PlaceOrderActivity.class);
        }
    }

    // 请求首页banner
    private Disposable reqBannerList() {
        return APIRetrofit.getDefault().reqHomeBannerList("1")
                .compose(RxUtil.<BaseResult2<List<Banner>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<Banner>>>() {
                    @Override
                    public void accept(BaseResult2<List<Banner>> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {

                        } else {

                        }
                        bannerList = listBaseResult2.getData();
                        adapter.notifyDataSetChanged();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // 请求文章列表
    private Disposable reqArticleList() {
        return APIRetrofit.getDefault().reqArticleList("1", 1, 999999)
                .compose(RxUtil.<BaseResult2<List<Article>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<Article>>>() {
                    @Override
                    public void accept(BaseResult2<List<Article>> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {

                        } else {

                        }
                        articleList = listBaseResult2.getData();
                        articleAapter.setDataList(articleList);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // banner adapter
    private class VpAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return bannerList.size();
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, final int position) {
            ImageView iv = new ImageView(getActivity());
            final ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            iv.setLayoutParams(params);
            iv.setScaleType(ImageView.ScaleType.CENTER_CROP);

//            iv.setImageResource(R.drawable.home_top_banner);
            GlideUtil.loadImg(Config.URL_IMG + bannerList.get(position).getPicture(), iv);

            container.addView(iv);
            //2020-11-24 轮播图点击事件,根据返回的url,跳转到文章详情页面
            iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(bannerList.get(position).getUrl()!=null){
                        Bundle bundle = new Bundle();
                        bundle.putString("articleId",bannerList.get(position).getUrl());
                        startActivity(ArticleDetailActivity.class, bundle);
                    }
                }
            });
            return iv;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((ImageView) object);
        }
    }

    // 特色项目特色套餐 tab adapter
    private class VpTabAdapter extends FragmentPagerAdapter {

        public VpTabAdapter(@NonNull FragmentManager fm) {
            super(fm);
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            if (position == 1) {
                return SpecialItemFragment.newInstance("2",vp_tab);
            }
            return SpecialItemFragment.newInstance("1",vp_tab);
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return HOME_MODELS[position];
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            mHandler.removeMessages(1);
        } else {
            mHandler.sendEmptyMessageDelayed(2, 500);
        }
    }

    private void refreshUnreadMsg() {
        APIRetrofit.getDefault().getUnreadMsg(Global.HEADER)
                .compose(RxUtil.<BaseResult2<List<UnreadData>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<UnreadData>>>() {
                    @Override
                    public void accept(BaseResult2<List<UnreadData>> res) throws Exception {
                        if (res.isSuccess()) {
                            if (res.getData() != null && res.getData().size() > 0 && 0 != res.getData().get(0).getCount()) {
                                vUnreadCount.setVisibility(View.VISIBLE);
                                vUnreadCount.setText(String.valueOf(res.getData().get(0).getCount()));
                            } else {
                                vUnreadCount.setVisibility(View.INVISIBLE);
                                vUnreadCount.setText("0");
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == Activity.RESULT_OK) {
            refreshUnreadMsg();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isHidden()) {
            mHandler.sendEmptyMessageDelayed(1, 6 * 1000);
            refreshUnreadMsg();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onPause() {
        super.onPause();
        mHandler.removeMessages(1);
    }
}